import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, NotFoundException } from '@nestjs/common';
import { FastifyRequest, FastifyReply } from 'fastify';
import { HistoryService } from './history.service';

@Catch(NotFoundException)
export class HistoryExceptionFilter implements ExceptionFilter {
  constructor(private readonly historyService: HistoryService) {}

  async catch(exception: NotFoundException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const request = ctx.getRequest<FastifyRequest>();
    const response = ctx.getResponse<FastifyReply>();
    const url = request.url;

    // 检查是否匹配 /user-history/:id 格式
    const historyRegex = /^\/user-history\/(\d+)(?:\?.*)?$/;
    const match = url.match(historyRegex);

    if (match) {
      const userId = parseInt(match[1], 10);

      // 获取查询参数
      const query = request.query as any;
      const page = parseInt(query.page, 10) || 1;
      const pageSize = parseInt(query.pageSize, 10) || 10;

      try {
        // 直接调用服务方法
        const result = await this.historyService.getUserHistory(userId, page, pageSize);
        return response.status(200).send({
          code: 200,
          message: 'success',
          data: result
        });
      }
      catch (error) {
        return response.status(HttpStatus.INTERNAL_SERVER_ERROR).send({
          code: HttpStatus.INTERNAL_SERVER_ERROR,
          message: error.message || '服务器内部错误',
          data: null
        });
      }
    }

    // 不匹配时，继续原来的异常处理
    const status = exception instanceof HttpException
      ? exception.getStatus()
      : HttpStatus.INTERNAL_SERVER_ERROR;

    return response.status(status).send({
      code: status,
      message: exception.message,
      data: null
    });
  }
} 